package top.kaoshanji.p1ch02d;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

/**
 * author kaoshanji
 * ^_^
 * create time 2025/1/3 18:53
 */
public class MethodHandlesExample09 {

    private static final Logger logger = LogManager.getLogger(MethodHandlesExample09.class);

    public static void main(String[] args) throws Throwable {

        new MethodHandlesExample09().catchExceptions();

    }

    public void catchExceptions() throws Throwable {
        logger.info("...代码清单 p1ch02d-09：MethodHandles#catchException的使用示例...");

        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodType typeTarget = MethodType.methodType(int.class, String.class);
        MethodHandle mhParseInt = lookup.findStatic(Integer.class, "parseInt", typeTarget);

        MethodType typeHandler = MethodType.methodType(int.class, Exception.class, String.class);
        MethodHandle mhHandler = lookup.findVirtual(MethodHandlesExample09.class, "handleException", typeHandler).bindTo(this);
        MethodHandle mh = MethodHandles.catchException(mhParseInt, NumberFormatException.class, mhHandler);

        mh.invoke("Hello");
    }

    public int handleException(Exception e, String str) {
        System.out.println(e.getMessage());
        return 0;
    }


}
